<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>


    <el-card>
      <el-alert
        title="注意：只允许为第三级设置相关参数"
        type="warning" show-icon :closable="false">
      </el-alert>


      <!--选择商品分类区域-->
      <el-row class="car-opt">
        <el-col>
          <span>请选择商品分类：</span>
          <el-cascader
            v-model="selectKeys"
            :options="selectedOption"
            expand-trigger="hover"
            :props="cascaderProps"
            @change="parentsCateChange"></el-cascader>
        </el-col>
      </el-row>


      <!--tab页签区域-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">

          <el-button type="primary" size="mimi" :disabled="isBtnDisabled" class="btn_many"
                     @click="addDialogVisible=true">添加参数
          </el-button>
          <!--动态属性-->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,ids) in scope.row.attr_vals" :key="ids" closable
                        @close="handleParamsClose(scope.row,ids)">
                  {{ item }}
                </el-tag>

                <!--输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row) "
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>

            </el-table-column>
            <el-table-column
              type="index">
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mimi" @click="showEditDialog(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mimi" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">

          <el-button type="primary" size="mimi" :disabled="isBtnDisabled" class="btn_only"
                     @click="addDialogVisible=true">添加属性
          </el-button>

          <!--静态属性-->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">

                <template slot-scope="scope">
                  <el-tag v-for="(item,ids) in scope.row.attr_vals" :key="ids" closable
                          @close="handleParamsClose(scope.row,ids)">
                    {{ item }}
                  </el-tag>

                  <!--输入文本框-->
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row) "
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                  </el-button>
                </template>


            </el-table-column>
            <el-table-column
              type="index">
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称">
            </el-table-column>
            <el-table-column
              label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mimi" @click="showEditDialog(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mimi" @click="removeParams(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>


    <!--添加参数的对话框-->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="ruleForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
    </el-dialog>
    <!--添加编辑的对话框-->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editDialogRuleForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      selectKeys: [],
      selectedOption: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      activeName: 'many',
      cateId: 0,
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false,
      addForm: {},
      addFormRules: {
        attr_name: [{required: true, message: '请输入参数名称', trigger: 'blur'},]
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [{required: true, message: '请输入参数名称', trigger: 'blur'}]
      },
      //控制文本框
      inputVisible: false,
      //文本框输入的内容
      inputValue: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const {data: res} = await this.$http.get('categories')
      if (res.meta.status === 200) {
        this.selectedOption = res.data
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    parentsCateChange() {

      this.getParamsData();
    },
    handleTabClick(tab, event) {

      console.log(this.activeName);
      this.getParamsData()
    },
    async getParamsData() {
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }

      this.cateId = this.selectKeys[this.selectKeys.length - 1]
      console.log(this.cateId);
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`, {params: {sel: this.activeName}})

      if (res.meta.status === 200) {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ?
            item.attr_vals.split(" ") : []
          item.inputVisible = false
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.manyTableData = res.data
          console.log(this.manyTableData)
        } else {
          this.onlyTableData = res.data
        }
      } else {
        return this.$message.error(res.meta.msg)
      }
    },
    addDialogClosed() {
      this.$refs.ruleForm.resetFields()
    },
    addParams() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName,
            })
          if (res.meta.status === 201) {
            this.getParamsData()
            this.$message.success(res.meta.msg)
          } else {
            this.$message.error(res.meta.msg)
          }
        } else {
          return
        }
      })
      console.log(this.$refs.ruleForm)
      this.addDialogVisible = false
    },
    async showEditDialog(id) {
      //查询当前参数的信息
      const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {params: {attr_sel: this.activeName}})
      if (res.meta.status === 200) {
        this.editForm = res.data
      } else {
        this.$message.error(res.meta.msg)
      }

      this.editDialogVisible = true
    },
    editDialogClosed() {
      this.$refs.editDialogRuleForm.resetFields()
    },
    editParams() {
      this.$refs.editDialogRuleForm.validate(async (valid) => {

        if (valid) {
          const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
            {attr_sel: this.activeName, attr_name: this.editForm.attr_name})
          if (res.meta.status == 200) {
            this.$message.success('修改成功')
            this.getParamsData()
            this.editDialogVisible = false
          }
        } else {
          return
        }
      })

    },
    async removeParams(id) {
      const str = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => console.log(err))
      if (str === 'confirm') {
        const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)

          this.getParamsData()
        } else {
          this.$message.error(res.meta.msg)
        }
      }
    },
    async handleParamsClose(item, i) {
      item.attr_vals.splice(i, 1)
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${item.attr_id}`, {
        attr_name: item.attr_name, attr_sel: item.attr_sel, attr_vals: item.attr_vals.join(' ')
      })

      if (res.meta.status == 200) {


        this.$message.success('修改成功')
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    async handleInputConfirm(item) {
      if (item.inputValue.trim().length == 0) {
        item.inputValue = ''
        item.inputVisible = false
        return
      }
      item.attr_vals.push(item.inputValue.trim())
      item.inputValue = ''
      item.inputVisible = false
      console.log(this.cateId, item.attr_id)
      console.log(Array.isArray(item.attr_vals))
      const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${item.attr_id}`, {
        attr_name: item.attr_name, attr_sel: item.attr_sel, attr_vals: item.attr_vals.join(' ')
      })

      if (res.meta.status == 200) {


        this.$message.success('修改成功')
      } else {
        this.$message.error(res.meta.msg)
      }
    },
    showInput(item) {
      item.inputVisible = true
      //让文本框自动获取焦点
      //$nextTick方法的作用，就是当页面上元素被重新渲染后，才会指定回调函数中的的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.selectKeys.length !== 3) {
        return true;
      } else {
        return false;
      }
    }
    ,
    titleText() {
      if (this.activeName === "many") {
        return "动态参数"
      } else {
        return "静态属性"
      }
    },


  }
}
</script>

<style lang="less" scoped>
.car-opt {
  margin: 15px 20px;
}

.btn_many {
  margin-bottom: 15px;
}

.btn_only {
  margin-bottom: 15px;
}

.el-tag {
  margin: 10px;
}

.input-new-tag {
  width: 90px;
  margin: 10px;
  vertical-align: bottom;
}

.button-new-tag {
  margin: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
</style>
